/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAPopularItemsViewController.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/16/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAPopularItemsViewController.h"
#import "BARPCManager.h"
#import "BACollection.h"
#import "BARecord.h"
#import "BASearchResultCell.h"
#import "BACoverUrlAndAvailabilityMemoryCache.h"
#import "InfoGalleriImageUrlUtils.h"
#import "BASlideInViewController.h"
#import "BAMaterialViewController.h"
#import "BAPopular.h"
#import "BALibrarySettings.h"
#import "BARootViewController.h"
#import "BAPatronSettings.h"


@interface BAPopularItemsViewController (){
    NSMutableSet* currentImageLoaders;
}
@property (nonatomic, strong) NSArray* popularItems;
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) UIActivityIndicatorView* activityIndicator;
@property (nonatomic, strong) UILabel* materialTypeLabel;
@property (nonatomic, strong) UIImageView* materialTypeImage;
@property (nonatomic, strong) UIView* headerContainerView;
@property (nonatomic, strong) UIView* rigthSeparatorA;
@property (nonatomic, strong) UIView* rigthSeparatorB;

@end

@implementation BAPopularItemsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _tableView = [UITableView new];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.view addSubview:self.tableView];
    
    _rigthSeparatorA = [UIView new];
    [self.view addSubview:self.rigthSeparatorA];
    self.rigthSeparatorA.backgroundColor = [UIColor colorWithWhite:0.76 alpha:1];
    self.rigthSeparatorA.translatesAutoresizingMaskIntoConstraints=NO;
    
    
    _headerContainerView = [UIView new];
    [self.headerContainerView setBackgroundColor:[UIColor clearColor]];
    [self.headerContainerView setAlpha:0];
    [self.view addSubview:self.headerContainerView];
    
    self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
    self.headerContainerView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[headerContainerView]|" options:0 metrics: 0 views:@{@"headerContainerView":self.headerContainerView}]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[tableView][rigthSeparator(1)]|" options:0 metrics: 0 views:@{@"tableView":self.tableView,@"rigthSeparator":self.rigthSeparatorA}]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[rigthSeparator]|" options:0 metrics: 0 views:@{@"rigthSeparator":self.rigthSeparatorA}]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerContainerView(35)][tableView]|" options:0 metrics: 0 views:@{@"headerContainerView":self.headerContainerView, @"tableView":self.tableView}]];
    
    
    _rigthSeparatorB = [UIView new];
    [self.headerContainerView addSubview:self.rigthSeparatorB];
    self.rigthSeparatorB.backgroundColor = [[BALibrarySettings instance] getCustomerColorNormal];
    self.rigthSeparatorB.translatesAutoresizingMaskIntoConstraints=NO;
    [self.headerContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[rigthSeparatorB(1)]|" options:0 metrics: 0 views:@{@"rigthSeparatorB":self.rigthSeparatorB}]];
    [self.headerContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[rigthSeparatorB]|" options:0 metrics: 0 views:@{@"rigthSeparatorB":self.rigthSeparatorB}]];
    
    
    _materialTypeImage = [UIImageView new];
    [self.materialTypeImage setContentMode:UIViewContentModeCenter];
    self.materialTypeImage.hidden=YES; //FIXME: temp removed for clarity

    _materialTypeLabel = [UILabel new];
    [self.materialTypeLabel setTextColor:[UIColor whiteColor]];
    //[self.materialTypeLabel setTextColor:[UIColor colorWithWhite:0.33 alpha:1]];
    self.materialTypeLabel.backgroundColor = [UIColor clearColor];
    [self.materialTypeLabel setFont:BA_FONT_MEDIUM(14)];
    UIView *materialTypeLabelContainer = [UIView new];
    [materialTypeLabelContainer setBackgroundColor:[BALibrarySettings instance].getCustomerColorDark];
    //[materialTypeLabelContainer setBackgroundColor:[UIColor colorWithWhite:0.81 alpha:1]];
    [materialTypeLabelContainer addSubview:self.materialTypeLabel];
    
    [self.headerContainerView addSubview:self.materialTypeImage];
    [self.headerContainerView addSubview:materialTypeLabelContainer];
    
    materialTypeLabelContainer.translatesAutoresizingMaskIntoConstraints = NO;
    self.materialTypeLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.materialTypeImage.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.headerContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-3-[materialTypeImage]-3-|" options:0 metrics: 0 views:@{@"materialTypeImage":self.materialTypeImage}]];
    [self.headerContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[materialTypeLabelContainer]|" options:0 metrics: 0 views:@{@"materialTypeLabelContainer":materialTypeLabelContainer}]];
    [self.headerContainerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[materialTypeImage(0)][materialTypeLabelContainer]-1-|" options:0 metrics: 0 views:@{@"materialTypeImage":self.materialTypeImage, @"materialTypeLabelContainer":materialTypeLabelContainer}]];
    
    [materialTypeLabelContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-20-[materialTypeLabel]" options:0 metrics: 0 views:@{@"materialTypeLabel":self.materialTypeLabel}]];
    
    [materialTypeLabelContainer addConstraint:[NSLayoutConstraint
                                               constraintWithItem:self.materialTypeLabel
                                               attribute:NSLayoutAttributeCenterY
                                               relatedBy:NSLayoutRelationEqual
                                               toItem:materialTypeLabelContainer
                                               attribute:NSLayoutAttributeCenterY
                                               multiplier:1.0f
                                               constant:0.0f]];
    
    
    
    currentImageLoaders=[NSMutableSet new];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setAlpha:0];
   
    if (RD_IS_IPAD) {
        [self.tableView registerNib:[UINib nibWithNibName:@"BASearchResultCell_iPad" bundle:nil] forCellReuseIdentifier:@"SearchResultCellNormal"];
        [self.tableView registerNib:[UINib nibWithNibName:@"BASearchResultCell_iPad" bundle:nil] forCellReuseIdentifier:@"SearchResultCellExpanded"];
    } else {
        [self.tableView registerNib:[UINib nibWithNibName:@"BASearchResultCell_iPhone" bundle:nil] forCellReuseIdentifier:@"SearchResultCellNormal"];
        [self.tableView registerNib:[UINib nibWithNibName:@"BASearchResultCell_iPhone" bundle:nil] forCellReuseIdentifier:@"SearchResultCellExpanded"];
    }

    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableWithNotification:) name:BA_COVER_URL_CACHE_IMAGE_LOADED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNewCoverUrls:) name:BA_COVER_URL_CACHE_COVER_URLS_ARRIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableWithNotification:) name:BA_AVAILAIBILITY_CACHE_AVAILABILITIES_ARRIVED object:nil];
    
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_COVER_URL_CACHE_IMAGE_LOADED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_COVER_URL_CACHE_COVER_URLS_ARRIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_AVAILAIBILITY_CACHE_AVAILABILITIES_ARRIVED object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    if (self.activityIndicator == nil) {
        //UIView* rootView = self.view.superview;
        
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [self.view addSubview:self.activityIndicator];
        [self.view sendSubviewToBack:self.activityIndicator];
        [self.activityIndicator startAnimating];
        self.activityIndicator.hidesWhenStopped = YES;
        
        self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO;
        
        [self.view addConstraint:[NSLayoutConstraint
                                 constraintWithItem:self.activityIndicator
                                 attribute:NSLayoutAttributeCenterX
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:self.view
                                 attribute:NSLayoutAttributeCenterX
                                 multiplier:1.0f
                                 constant:0.0f]];
        
        [self.view addConstraint:[NSLayoutConstraint
                                 constraintWithItem:self.activityIndicator
                                 attribute:NSLayoutAttributeCenterY
                                 relatedBy:NSLayoutRelationEqual
                                 toItem:self.view
                                 attribute:NSLayoutAttributeCenterY
                                 multiplier:1.0f
                                 constant:0.0f]];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)clearAndSetIsLoading
{
    [self setPopular:nil];
    [self.activityIndicator startAnimating];
}

-(void)setPopular:(BAPopular *)popular{
    _popular = popular;
    
    if (popular != nil) {
        [self.materialTypeLabel setText:popular.title];
        
        UIImage* iconImage = [[BALibrarySettings instance] getIconForMaterialType:popular.type
                                                                contextIdentifier:BATypeIconContextIPadSearchColumnHeader
                                                                            color:[BALibrarySettings instance].getCustomerColorDark]; //FIXME: not used for now
        [self.materialTypeImage setImage:iconImage];
        
        NSMutableArray* records = [NSMutableArray new];
        
        for (BACollection* collection in popular.searchResult.data) {
            for (BARecord* record in collection.records) {
                [records addObject:record];
            }
        }
        
        if (popular.searchResult.count > 0) {
            [self fetchAvailabilityForSearchResults:records];
            [self fetchCoverUrlsForSearchResults:records];
        }
        
        
        _popularItems = [NSArray arrayWithArray:records];
        [self.tableView reloadData];
        [UIView animateWithDuration:0.3 animations:^{
            [self.tableView setAlpha:1];
            [self.headerContainerView setAlpha:1];
        } completion:^(BOOL finished) {
            [self.activityIndicator stopAnimating];
        }];
        
    } else {
        //empty lists
        [self.materialTypeLabel setText:@""];
        [self.materialTypeImage setImage:nil];
        
        _popularItems = nil;
        [self.tableView reloadData];
        [self.activityIndicator stopAnimating];
    }
}


-(void)fetchAvailabilityForSearchResults:(NSArray*)records
{
    NSMutableArray* identifiers = [NSMutableArray new];
    
    for (BARecord* record in records) {
        [identifiers addObject:record.identifier];
    }
    
    [BARPCManager getAvailabilityAsyncFromView:self
                                   identifiers:identifiers
                            includeHoldingInfo:NO
                                   resultBlock:^(NSDictionary *result) {
                                       [self appendAvailabilityRecords:result];
                                   }
                                    errorBlock:^(int errorCode, NSString *errorMessage) {
                                        DLog(@"error fetching availability %d %@",errorCode, errorMessage);
                                    }];
    
    
}

-(void)fetchCoverUrlsForSearchResults:(NSArray*)records
{
    NSMutableArray* identifiers = [NSMutableArray new];
    
    for (BARecord* record in records) {
        [identifiers addObject:record.identifier];
    }
    
    [[BACoverUrlAndAvailabilityMemoryCache instance] fetchCoverUrlsForIdentifiers:identifiers];
    
    /*
    [BARPCManager getCoverUrlsAsyncFromView:self
                            coverUrlQueries:identifiers
                                resultBlock:^(NSDictionary* result) {
                                    [self appendCoverUrls:result];
                                }
                                 errorBlock:^(int errorCode, NSString *errorMessage) {
                                     DLog(@"error fetching coverurls %d %@",errorCode, errorMessage);
                                 }];
    */
}

-(void)appendAvailabilityRecords:(NSDictionary *)availabilities
{
    [[BACoverUrlAndAvailabilityMemoryCache instance] appendAvailabilityRecords:availabilities];
    
    [self.tableView reloadData];
}

-(void)appendCoverUrls:(NSDictionary *)coverUrls
{
    [[BACoverUrlAndAvailabilityMemoryCache instance] appendCoverUrls:coverUrls];
    
    [self.tableView reloadData];
}

-(void)handleNewCoverUrls:(id)sender
{
    NSArray* visibleCells = [self.tableView visibleCells];
    NSMutableArray* visibleIdentifiers = [NSMutableArray new];
    
    for (BASearchResultCell* cell in visibleCells) {
        if ([cell isKindOfClass:[BASearchResultCell class]]) {
            if (cell.record && [cell.record.identifier length]>0) {
                [visibleIdentifiers addObject:cell.record.identifier];
            }
        }
    }
    [[BACoverUrlAndAvailabilityMemoryCache instance] fetchCoverImagesForIdentifiers:visibleIdentifiers];
}

-(void)reloadTableWithNotification:(id)sender
{
    [self.tableView reloadData];
}

#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.popularItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isExpanded = [self shouldCellBeExpandedForIndexPath:indexPath];
    BASearchResultCell* cell = nil;
    if (isExpanded) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCellExpanded"];
    } else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCellNormal"];
    }
    
    cell.isShowingMoreView = isExpanded; //must be called before setRecord
    
    BARecord* record = [self.popularItems objectAtIndex:indexPath.row];
    [cell setRecord:record];
    
    BACoverUrlAndAvailabilityMemoryCache* cache = [BACoverUrlAndAvailabilityMemoryCache instance];
    
    BAAvailability* availabilityInfo = [cache getAvailabilityForIdentifier:record.identifier];
    if (availabilityInfo) {
        [cell setAvailability:availabilityInfo];
    }
    
    [cache fetchCoverImagesForIdentifiers:@[record.identifier]];
   
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BOOL isExpanded = [self shouldCellBeExpandedForIndexPath:indexPath];
    
    if (RD_IS_IPAD) {
        if (isExpanded) {
            return BA_SEARCH_RESULT_CELL_EXPANDED_HEIGHT_IPAD;
        } else {
            return BA_SEARCH_RESULT_CELL_DEFAULT_HEIGHT_IPAD;
        }
    } else {
        //iphone
        if (isExpanded) {
            return BA_SEARCH_RESULT_CELL_EXPANDED_HEIGHT_IPHONE;
        } else {
            return BA_SEARCH_RESULT_CELL_DEFAULT_HEIGHT_IPHONE;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BARecord* rec = [self.popularItems objectAtIndex:indexPath.row];
    
    BASlideInViewController *slideIn = [BASlideInViewController findSlideInViewController:self];
    
    
    if (slideIn != nil && rec != nil) {
        UIViewController<BAMaterialViewControllerProtocol>* mvc = [[BARootViewController instance] createMaterialViewController];// [BAMaterialViewController new];
        [slideIn slideInViewController:mvc animated:YES completion:nil];
        
        BACoverUrlAndAvailabilityMemoryCache* cache = [BACoverUrlAndAvailabilityMemoryCache instance];
        
        BACoverUrl* cu_object = [cache getCoverUrlForIdentifier:rec.identifier];
        BAAvailability* availability = [cache getAvailabilityForIdentifier:rec.identifier];
        UIImage* currentImage = [cache getSearchResultCellSizedCoverImageForIdentifier:rec.identifier];
        [mvc showRecord:rec withCoverUrl:cu_object.url currentImage:currentImage availability:availability];
    
    }
}

-(BOOL)shouldCellBeExpandedForIndexPath:(NSIndexPath *)indexPath
{
    
    BARecord* record =  [self.popularItems objectAtIndex:indexPath.row];
    BAPatronSettings* patronsettings = [BAPatronSettings instance];
    BOOL isExpanded = (record.moreInSameSeries && [patronsettings isUserAllowedLibrarianAccessForCurrentLibrary]) || [patronsettings isUserAllowedIMFEditorAccessForCurrentLibrary];
    
    return isExpanded;
}

-(void)setRightSeparatorHidden:(BOOL)isHidden
{
    [self view];
    self.rigthSeparatorA.hidden = isHidden;
    self.rigthSeparatorB.hidden = isHidden;
}


@end
